package com.zc.gateway.service;

import as.leap.vertx.rpc.impl.RPCClientOptions;
import as.leap.vertx.rpc.impl.VertxRPCClient;
import com.zc.common.ClusterVertx;
import com.zc.common.RPCService;
import com.zc.common.annotations.VerticleMapping;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@VerticleMapping
@Service
public class RouterService {
    private Logger logger = LoggerFactory.getLogger(RouterService.class);
    /**
     * 获得所有路由服务
     * @return
     */
    @Transactional(readOnly = true)
    public JsonObject doGetServiceTest(JsonObject param) throws Exception{
       /* JsonObject result=new JsonObject();
        result.put("ob",new HashMap(){{put("key","serviceName");put("key1","serviceName1");put("key2","serviceName2");put("key3","serviceName3");put("key4","serviceName4");}});
        System.out.println("this is Cluster1 services,"+this.getClass().getName()+"'s doGetServiceTest method return bace!");
        return new JsonObject(Json.encode(result));*/
        JsonObject result=new JsonObject();//这里的结果需要rpc返回值
        RPCClientOptions<RPCService> rpcClientOptions = new RPCClientOptions<RPCService>( ClusterVertx.getClusterVertx()).setBusAddress("rpc.user").setServiceClass(RPCService.class);
        RPCService myService = new VertxRPCClient<>(rpcClientOptions).bindService();
        try {
            myService.asyncService(new JsonObject(),"userInfo", event -> {
                System.out.println("远程调用应用中心asyncService方法1:"+event.result());
            });
            result=myService.futureService(new JsonObject(), "userInfo").get(5000, TimeUnit.MILLISECONDS);
            System.out.println("远程调用应用中心futureService方法:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("远程调用失败,{}", e);
        }
        return result;
    }

    /**
     * 获得所有路由服务
     * @return
     */
    @Transactional(readOnly = true)
    public JsonObject doGetValueTest(JsonObject param) throws Exception{
        JsonObject result=new JsonObject();
        result.put("ob",new HashMap(){{put("key","val");put("key1","val1");put("key2","val2");put("key3","val3");put("key4","val4");}});
        System.out.println("this is Cluster1 services,"+this.getClass().getName()+"'s doGetValueTest method return bace!");
        return new JsonObject(Json.encode(result));
    }
}
